/**
 * 文件名：CheckStyleService.java
 * 版权：Copyright Lightkit All Rights Reserved.
 * 描述：复制pre-commit到插件git hooks
 */
package com.lightkits.wms.checkstyle.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.SmartLifecycle;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * 复制pre-commit到插件git hooks
 *
 * @author yuchuan.zeng@hand-china.com
 * @version 1.0
 * @date 2018/8/3 14:08
 */
@Component
public class CheckStyleService implements SmartLifecycle {

    private static Logger logger = LoggerFactory.getLogger(CheckStyleService.class);

    private volatile boolean running = false;

    private static final int PHASE = 9999;

    private static final String PROJECT_NAME = "lightkits-center-service";
    private static final String FILE_NAME = "pre-commit.sh";
    private static final String TO_FILE_NAME = "pre-commit";
    private static final String SUFFIX = File.separator + ".git" + File.separator + "hooks";

    private static final int SIZE = 1024;

    private static final String OS_NAME = System.getProperty("os.name");

    private static final String OS_MAC = "Mac OS";
    private static final String OS_LINUX = "Linux";

    @Override
    public boolean isAutoStartup() {
        return true;
    }

    @Override
    public void stop(Runnable runnable) {
        if (isRunning()) {
            running = false;
        }
        if (runnable != null) {
            runnable.run();
        }
    }

    @Override
    public void start() {
        if (!isRunning()) {
            logger.debug("=============== start copy file to hooks ================\n");
            String basePath = this.getClass().getResource("").getPath();
            int i = basePath.indexOf(PROJECT_NAME);
            if (i == -1) {
                logger.error("PROJECT_NAME找不到，程序异常");
                return;
            }
            int len = PROJECT_NAME.length();
            basePath = basePath.substring(0, i + len);
            String filePath = new StringBuffer(basePath).
                    append(File.separator).
                    append("checkstyle").
                    append(File.separator).
                    append(FILE_NAME).toString();

            File file = new File(filePath);
            if (!file.exists() || !file.isFile()) {
                logger.error("文件不存在 或者不是文件");
                return;
            }

            StringBuffer toDirPath = new StringBuffer().append(basePath).append(SUFFIX);
            File toDir = new File(toDirPath.toString());
            if (!toDir.exists()) {
                logger.error("目的目录不存在");
                return;
            }
            String toFilePath = toDirPath.append(File.separator).append(TO_FILE_NAME).toString();
            File toFile = new File(toFilePath);
//            if (toFile.exists()) {
//                //由于不敢保证pre-commit是否更新，每次启动都替换一下
//                return;
//            }
            try (FileInputStream sourceFile = new FileInputStream(file);
                 FileOutputStream targetFile = new FileOutputStream(toFile)) {
                byte[] b = new byte[SIZE];
                int a;
                while ((a = sourceFile.read(b)) != -1) {
                    targetFile.write(b, 0, a);
                }

                // 修改文件权限
                if (OS_NAME.indexOf(OS_MAC) > -1 || OS_NAME.indexOf(OS_LINUX) > -1) {
                    // 如果是MAC 或者 LINUX 修改目标文件的权限
                    String cmd = "chmod 770 " + toFile;
                    Process process = Runtime.getRuntime().exec(cmd);
                    int existValue = process.exitValue();
                    if (existValue != 0) {
                        logger.info("Change file permission failed.");
                    }
                }
            } catch (Exception e) {
                logger.error("迁移错误:", e);
            }
            running = true;
        }
    }

    @Override
    public void stop() {

    }

    @Override
    public boolean isRunning() {
        return running;
    }

    @Override
    public int getPhase() {
        return PHASE;
    }

}
